package com.annotation.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 *  使用基于注解版的事务
 *  1、想要使用基于注解版的事务管理，需要添加 @EnableTransactionManagement 注解开启事务管理功能
 *      但是只添加注解不配置事务管理器会报 NoSuchBeanDefinitionException，所以需要配置事务管理器
 *      org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.transaction.PlatformTransactionManager'
 *  2、在容器中添加事务管理器 PlatformTransactionManager
 */

@EnableTransactionManagement
@PropertySource(value = "classpath:jdbc.properties",encoding = "UTF-8")
@ComponentScan(value = "com.annotation.transaction")
@Configuration
public class MainConfigTransaction {

    @Value("${db.user}")
    private String user;

    @Value("${db.password}")
    private String password;

    @Value("${db.url}")
    private String url;

    @Value("${db.driverClass}")
    private String driverClass;

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
    public DataSource dataSource() throws PropertyVetoException {
        System.out.println("URL-->" + url);
        System.out.println("PASSWORD-->" + password);
        System.out.println("DRIVER_CLASS-->" + driverClass);
        System.out.println("USER-->" + user);
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(password);
        dataSource.setJdbcUrl(url);
        dataSource.setDriverClass(driverClass);
        return dataSource;
    }

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
    public JdbcTemplate jdbcTemplate(DataSource dataSource){
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        return jdbcTemplate;
    }

    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource){
        return  new DataSourceTransactionManager(dataSource);
    }

}
